/*
 * ManagedBlas.cs
 *
 * Managed provider for BLAS routines.
 *
 * Copyright (c) 2005, dnAnalytics. All rights reserved.
 */

namespace dnAnalytics.LinearAlgebra
{
    internal sealed class ManagedBlas : ISimplifiedBlas
    {
        public int AbsoluteMaximumIndex(double[] data)
        {
            int index = 0;
            double max = data[0];
            for (int i = 1; i < data.Length; i++)
            {
                double test = System.Math.Abs(data[i]);
                if (test > max)
                {
                    index = i;
                    max = test;
                }
            }
            return index;
        }

        public double SumMagnitudes(double[] data)
        {
            double ret = 0;
            for (int i = 0; i < data.Length; i++)
            {
                ret += System.Math.Abs(data[i]);
            }
            return ret;
        }

        public double DotProduct(double[] x, double[] y)
        {
            double ret = 0;
            for (int i = 0; i < x.Length; ++i)
            {
                ret += x[i] * y[i];
            }
            return ret;
        }

        public void Scale(double constant, double[] data)
        {
            for (int i = 0; i < data.Length; ++i)
            {
                data[i] *= constant;
            }
        }

        public void Subtract(double[] vector, double constant)
        {
            for (int i = 0; i < vector.Length; ++i)
            {
                vector[i] -= constant;
            }
        }

        public void Subtract(double[] x, double[] y)
        {
            for (int i = 0; i < x.Length; ++i)
            {
                x[i] -= y[i];
            }
        }

        public void Add(double[] vector, double constant)
        {
            for (int i = 0; i < vector.Length; ++i)
            {
                vector[i] += constant;
            }
        }

        public void Add(double[] x, double[] y)
        {
            for (int i = 0; i < x.Length; ++i)
            {
                x[i] += y[i];
            }
        }

        public void Multiply(int m, int n, int k, double[] x, double[] y, double[] result)
        {
            int i, j, l;
            double s = 0;
            int ntmp = 0;
            int mtmp = 0;
            for (j = 0; j < n; ++j)
            {
                ntmp = k * j;
                mtmp = m * j;
                for (i = 0; i < m; ++i)
                {
                    s = 0;
                    for (l = 0; l < k; ++l)
                    {
                        s += x[m * l + i] * y[ntmp + l];
                    }
                    result[mtmp + i] = s;
                }
            }
        }
    }
}